<template>
  <div class="base-warehouse-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>仓库管理</span>
          <el-button type="primary" @click="handleAdd" :loading="store.loading">
            <el-icon><Plus /></el-icon>
            新增仓库
          </el-button>
        </div>
      </template>

      <!-- 搜索筛选区域 -->
      <div class="search-form">
        <el-form :model="searchForm" inline label-width="80px">
          <el-form-item label="仓库编码">
            <el-input
              v-model="searchForm.warehouseCode"
              placeholder="请输入仓库编码"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="仓库名称">
            <el-input
              v-model="searchForm.warehouseName"
              placeholder="请输入仓库名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="仓库类型">
            <el-select
              v-model="searchForm.warehouseType"
              placeholder="请选择仓库类型"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="option in store.warehouseTypeOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.isActive"
              placeholder="请选择状态"
              clearable
              style="width: 200px"
            >
              <el-option label="激活" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table
        v-loading="store.loading"
        :data="store.filteredWarehouses"
        style="width: 100%"
        border
      >
        <el-table-column prop="warehouseCode" label="仓库编码" width="150" />
        <el-table-column prop="warehouseName" label="仓库名称" width="180" />
        <el-table-column prop="warehouseType" label="仓库类型" width="120">
          <template #default="{ row }">
            {{ getWarehouseTypeLabel(row.warehouseType) }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="仓库地址" min-width="200" />
        <el-table-column prop="contactPerson" label="联系人" width="100" />
        <el-table-column prop="contactPhone" label="联系电话" width="120" />
        <el-table-column prop="area" label="仓库面积(㎡)" width="120">
          <template #default="{ row }">
            {{ row.area || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="manager" label="仓库管理员" width="120">
          <template #default="{ row }">
            {{ row.manager || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="isActive" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.isActive"
              active-value="1"
              inactive-value="0"
              @change="(value: number) => handleStatusChange(row.warehouseId, value)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
              :loading="store.loading"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
              :loading="store.loading"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="store.currentPage"
          v-model:page-size="store.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="store.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑仓库对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="仓库编码" prop="warehouseCode">
          <el-input
            v-model="formData.warehouseCode"
            placeholder="请输入仓库编码"
            :disabled="dialogType === 'edit'"
          />
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="formData.warehouseName" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="仓库类型" prop="warehouseType">
          <el-select v-model="formData.warehouseType" placeholder="请选择仓库类型">
            <el-option
              v-for="option in store.warehouseTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入仓库地址" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="formData.contactPerson" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="仓库面积(㎡)" prop="area">
          <el-input
            v-model="formData.area"
            type="number"
            placeholder="请输入仓库面积"
            min="0"
            step="0.01"
          />
        </el-form-item>
        <el-form-item label="仓库容量" prop="capacity">
          <el-input
            v-model="formData.capacity"
            type="number"
            placeholder="请输入仓库容量"
            min="0"
            step="0.01"
          />
        </el-form-item>
        <el-form-item label="管理员ID" prop="managerId">
          <el-input
            v-model="formData.managerId"
            type="number"
            placeholder="请输入管理员ID"
            min="0"
          />
        </el-form-item>
        <el-form-item label="管理员姓名" prop="manager">
          <el-input v-model="formData.manager" placeholder="请输入管理员姓名" />
        </el-form-item>
        <el-form-item label="是否激活" prop="isActive">
          <el-switch
            v-model="formData.isActive"
            active-value="1"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="store.loading">
          {{ dialogType === 'add' ? '确定添加' : '确定修改' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useBaseWarehouseStore, getWarehouseTypeLabel } from '@/stores/base/BaseWarehouseStore'
import type { baseWarehouse } from '@/types/base/BaseWarehouse'

// Store
const store = useBaseWarehouseStore()

// 搜索表单
const searchForm = reactive({
  warehouseCode: '',
  warehouseName: '',
  warehouseType: undefined,
  isActive: undefined
})

// 对话框状态
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const dialogTitle = computed(() => dialogType.value === 'add' ? '新增仓库' : '编辑仓库')

// 表单数据和验证规则
const formData = reactive<Partial<baseWarehouse>>({
  warehouseCode: '',
  warehouseName: '',
  warehouseType: 1,
  address: '',
  contactPerson: '',
  contactPhone: '',
  area: undefined,
  capacity: undefined,
  managerId: undefined,
  manager: '',
  isActive: 1
})

const formRules = {
  warehouseCode: [
    { required: true, message: '请输入仓库编码', trigger: 'blur' },
    { min: 1, max: 50, message: '仓库编码长度不能超过50个字符', trigger: 'blur' }
  ],
  warehouseName: [
    { required: true, message: '请输入仓库名称', trigger: 'blur' },
    { min: 1, max: 100, message: '仓库名称长度不能超过100个字符', trigger: 'blur' }
  ],
  warehouseType: [
    { required: true, message: '请选择仓库类型', trigger: 'change' }
  ],
  contactPhone: [
    { min: 1, max: 20, message: '联系电话长度不能超过20个字符', trigger: 'blur' }
  ]
}

const formRef = ref()

// 初始化数据
onMounted(() => {
  loadData()
})

// 加载数据
const loadData = async () => {
  try {
    await store.fetchWarehouses()
  } catch (error) {
    ElMessage.error('加载数据失败')
  }
}

// 搜索
const handleSearch = () => {
  store.setSearchParams({
    warehouseCode: searchForm.warehouseCode,
    warehouseName: searchForm.warehouseName,
    warehouseType: searchForm.warehouseType ? Number(searchForm.warehouseType) : undefined,
    isActive: searchForm.isActive ? Number(searchForm.isActive) : undefined
  })
  loadData()
}

// 重置搜索条件
const handleReset = () => {
  // 修复错误2322：不能将类型"undefined"分配给类型"never"
  searchForm.warehouseCode = ''
  searchForm.warehouseName = ''
  searchForm.warehouseType = undefined
  searchForm.isActive = undefined

  store.resetSearchParams()
  loadData()
}

// 分页处理
const handleSizeChange = (size: number) => {
  store.setPagination(1, size)
  loadData()
}

const handleCurrentChange = (current: number) => {
  store.setPagination(current, store.pageSize)
  loadData()
}

// 打开新增对话框
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = async (row: baseWarehouse) => {
  dialogType.value = 'edit'
  try {
    const warehouse = await store.fetchWarehouseById(row.warehouseId)
    Object.assign(formData, warehouse)
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取仓库详情失败')
  }
}

// 删除仓库
const handleDelete = async (row: baseWarehouse) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除仓库 "${row.warehouseName}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await store.deleteWarehouse(row.warehouseId)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 切换仓库状态
const handleStatusChange = async (warehouseId: number, isActive: number) => {
  try {
    await store.toggleWarehouseStatus(warehouseId, isActive)
    ElMessage.success(isActive === 1 ? '激活成功' : '禁用成功')
  } catch (error) {
    ElMessage.error(isActive === 1 ? '激活失败' : '禁用失败')
    // 恢复状态
    loadData()
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    if (dialogType.value === 'add') {
      await store.createWarehouse(formData as Omit<baseWarehouse, 'warehouseId' | 'createdAt' | 'updatedAt' | 'isDeleted'>)
      ElMessage.success('添加成功')
    } else {
      if (!formData.warehouseId) {
        throw new Error('仓库ID不存在')
      }
      await store.updateWarehouse(formData.warehouseId, formData)
      ElMessage.success('修改成功')
    }
    dialogVisible.value = false
    loadData()
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : '操作失败'
    ElMessage.error(errorMessage)
  }
}

// 取消对话框
const handleCancel = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    warehouseCode: '',
    warehouseName: '',
    warehouseType: 1,
    address: '',
    contactPerson: '',
    contactPhone: '',
    area: undefined,
    capacity: undefined,
    managerId: undefined,
    manager: '',
    isActive: 1,
    warehouseId: undefined,
    createdAt: undefined,
    updatedAt: undefined,
    isDeleted: undefined
  })
}

// 格式化日期
const formatDate = (date: Date | string): string => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`
}
</script>

<style scoped>
.base-warehouse-page {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
